package com.lmpop.frame.util;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class SetCharacterEncodingFilter extends HttpServlet
  implements Filter
{
  private static final long serialVersionUID = 1L;
  protected String encoding;
  protected FilterConfig filterConfig;

  public SetCharacterEncodingFilter()
  {
    this.encoding = null;
    this.filterConfig = null;
  }

  public void destroy()
  {
    this.encoding = null;
    this.filterConfig = null;
  }

  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
    throws IOException, ServletException
  {
    HttpServletRequest httpreq = (HttpServletRequest)request;
    if ((httpreq.getMethod().equals("POST")) || (httpreq.getMethod().equals("GET")))
      request.setCharacterEncoding(this.encoding);
    else {
      request = new Request(httpreq);
    }

    chain.doFilter(request, response);
  }

  public void init(FilterConfig filterConfig)
    throws ServletException
  {
    this.filterConfig = filterConfig;
    this.encoding = filterConfig.getInitParameter("encoding");
  }

  class Request extends HttpServletRequestWrapper
  {
    public Request(HttpServletRequest request) {
		super(request);
	}

	public String encoding(String input)
    {
      try
      {
        byte[] bytes = input.getBytes("ISO-8859-1");
        return new String(bytes, SetCharacterEncodingFilter.this.encoding);
      }
      catch (Exception ex) {
      }
      return null;
    }

    private HttpServletRequest getHttpServletRequest()
    {
      return (HttpServletRequest)super.getRequest();
    }

    public String getParameter(String name)
    {
      return encoding(getHttpServletRequest().getParameter(name));
    }

    public String[] getParameterValues(String name)
    {
      String[] values = getHttpServletRequest().getParameterValues(name);
      if (values != null) {
        for (int i = 0; i < values.length; i++) {
          values[i] = encoding(values[i]);
        }
      }
      return values;
    }
  }
}